package com.jackiepenghe.rangedatepickerlibrary

import android.graphics.drawable.Drawable
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.Calendar
import java.util.Date

/**
 * @author jackie
 */
internal class DataSelectRecyclerViewAdapter(
    private val gridLayoutManager: GridLayoutManager,
    private val monthDate: Date,
    private val dataRecyclerViewAdapter: DataRecyclerViewAdapter,
    private val onItemClickListener: OnItemClickListener? = null
) :
    RecyclerView.Adapter<DataSelectRecyclerViewAdapter.ViewHolder>() {

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 接口声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    internal interface OnItemClickListener {
        /**
         * 日期选项被点击了
         */
        fun onItemClicked(
            position: Int,
            dateString: String,
            date: Date,
            dataSelectRecyclerViewAdapter: DataSelectRecyclerViewAdapter
        )

    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 属性声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    private val dateList = ArrayList<String>()

    /**
     * 文本的大小
     */
    private var dateItemSize = 0f

    /**
     * 日期选项的item 正常的背景色
     */
    private var dateItemBackgroundNormal: Drawable? = null

    /**
     * 日期选项的item 选中的背景色
     */
    private var dateItemBackgroundSelect: Drawable? = null

    /**
     * 日期选项的item 空白文本的背景
     */
    private var dateItemBackgroundEmpty: Drawable? = null


    /**
     * 单选中一个日期时，日期的背景（不设置时，默认与dateItemBackgroundSelect一致）
     */
    private var dateItemBackgroundSingleSelect: Drawable? = null

    /**
     * 日期选项的item 文本大小
     */
    private var dateItemTextSize = 0f

    /**
     * 日期选项的item 正常文本颜色
     */
    private var dateItemTextColorNormal = 0

    /**
     * 日期选项的item 选中文本颜色
     */
    private var dateItemTextColorSelect = 0

    /**
     * 日期选项的item 未激活(不可选)时文本颜色
     */
    private var dateItemTextColorDisable = 0

    /**
     * 日期选项的item 选中的日期为起始日期时的背景
     */
    private var dateItemBackgroundStart: Drawable? = null

    /**
     * 日期选项的item 选中的日期为结束日期时的背景
     */
    private var dateItemBackgroundEnd: Drawable? = null

    /**
     * 日期选项的item 选中的日期为未激活(不可选)时的背景
     */
    private var dateItemBackgroundEndDisable: Drawable? = null

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 构造方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    init {
        calculateDateList()
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 内部类声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 实现方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.com_jackiepenghe_rangedatepickerlibrary_adapter_date_select_recycler_view,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val layoutPosition = holder.layoutPosition
        val itemView = holder.itemView
        val dateString = dateList[position]
        val textView =
            itemView.findViewById<TextView>(R.id.com_jackiepenghe_rangedatepickerlibrary_adapter_date_select_recycler_view_date_tv)
        textView.text =
            dateString
        val date = dateString.toDate(monthDate)
        resizeItemSize(holder, textView)
        setTextAttr(textView, date)
        date ?: return
        if (!date.isActive(dataRecyclerViewAdapter)) {
            return
        }
        itemView.setOnClickListener {
            Logger.log("date item clicked layoutPosition = $layoutPosition")
            onItemClickListener?.onItemClicked(
                layoutPosition,
                dateString,
                date,
                this
            )
        }
    }

    /**
     * Returns the total number of items in the data set held by the adapter.
     *
     * @return The total number of items in this adapter.
     */
    override fun getItemCount(): Int {
        return dateList.size
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 公开方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    internal fun setDateItemSize(dateItemSize: Float) {
        this.dateItemSize = dateItemSize
    }

    internal fun setDateItemBackgroundNormal(dateItemBackgroundNormalColor: Drawable?) {
        this.dateItemBackgroundNormal = dateItemBackgroundNormalColor
    }

    internal fun setDateItemBackgroundSelect(dateItemBackgroundSelectColor: Drawable?) {
        this.dateItemBackgroundSelect = dateItemBackgroundSelectColor
    }

    internal fun setDateItemTextSize(dateItemTextSize: Float) {
        this.dateItemTextSize = dateItemTextSize
    }

    internal fun setDateItemTextColorNormal(dateItemTextColorNormal: Int) {
        this.dateItemTextColorNormal = dateItemTextColorNormal
    }

    internal fun setDateItemTextColorSelect(dateItemTextColorSelect: Int) {
        this.dateItemTextColorSelect = dateItemTextColorSelect
    }

    internal fun setDateItemTextColorDisable(dateItemTextColorDisable: Int) {
        this.dateItemTextColorDisable = dateItemTextColorDisable
    }

    internal fun setDateItemBackgroundStart(dateItemBackgroundStart: Drawable?) {
        this.dateItemBackgroundStart = dateItemBackgroundStart
    }

    internal fun setDateItemBackgroundEnd(dateItemBackgroundEnd: Drawable?) {
        this.dateItemBackgroundEnd = dateItemBackgroundEnd
    }

    internal fun setDateItemBackgroundDisable(dateItemBackgroundEndDisable: Drawable?) {
        this.dateItemBackgroundEndDisable = dateItemBackgroundEndDisable
    }

    internal fun setDateItemBackgroundEmpty(dateItemBackgroundEmpty: Drawable?) {
        this.dateItemBackgroundEmpty = dateItemBackgroundEmpty
    }

    internal fun setDateItemBackgroundSingleSelect(dateItemBackgroundSingleSelect: Drawable?) {
        this.dateItemBackgroundSingleSelect = dateItemBackgroundSingleSelect
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 计算当月日子列表
     */
    private fun calculateDateList() {
        val calendar = Calendar.getInstance()
        calendar.time = monthDate
        calendar.set(Calendar.DAY_OF_MONTH, 1)
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
        for (i in 2..dayOfWeek) {
            dateList.add("")
        }
        calendar.roll(Calendar.DAY_OF_MONTH, -1)
        val maxDay = calendar.get(Calendar.DAY_OF_MONTH)
        for (i in 1..maxDay) {
            dateList.add(i.toString())
        }
        val cache = dateList.size % 7
        for (i in 0 until 7 - cache) {
            dateList.add("")
        }
    }

    /**
     * 重新计算item的大小
     */
    private fun resizeItemSize(holder: ViewHolder, textView: TextView) {
        val width = (gridLayoutManager.width / gridLayoutManager.spanCount.toFloat() + 1).toInt()
        val layoutParams = holder.itemView.layoutParams as GridLayoutManager.LayoutParams
        layoutParams.width = width
        layoutParams.height = width
        holder.itemView.layoutParams = layoutParams
        val layoutParams1 = textView.layoutParams as RelativeLayout.LayoutParams
        if (dateItemSize <= 0f) {
            layoutParams1.width = width
            layoutParams1.height = width
        } else {
            if (dateItemSize > width) {
                layoutParams1.width = width
                layoutParams1.height = width
            } else {
                layoutParams1.width = (dateItemSize + 0.5).toInt()
                layoutParams1.height = (dateItemSize + 0.5).toInt()
            }
        }
        textView.layoutParams = layoutParams1
    }

    private fun setTextAttr(textView: TextView, date: Date?) {
        setBackground(textView, date)
        setTextColor(textView, date)
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, dateItemTextSize)
    }

    private fun setTextColor(textView: TextView, date: Date?) {
        if (date?.isActive(dataRecyclerViewAdapter) != true
        ) {
            textView.setTextColor(dateItemTextColorDisable)
        } else {
            if (date.isSelect(dataRecyclerViewAdapter)) {
                textView.setTextColor(dateItemTextColorSelect)
            } else {
                textView.setTextColor(dateItemTextColorNormal)
            }
        }
    }

    private fun setBackground(textView: TextView, date: Date?) {
        if (date == null) {
            setEmptyBackground(textView)
        } else if (!date.isActive(dataRecyclerViewAdapter)) {
            setDisableBackground(textView)
        } else {
            if (date.isSelect(dataRecyclerViewAdapter)) {
                if (date.isStartDate(dataRecyclerViewAdapter)) {
                    setStartSelectBackground(textView)
                } else if (date.isEndDate(dataRecyclerViewAdapter)) {
                    setEndSelectBackground(textView)
                } else {
                    setSelectBackground(textView,date)
                }
            } else {
                setNormalBackground(textView)
            }
        }
    }

    private fun setStartSelectBackground(textView: TextView) {
        if (dateItemBackgroundStart != null) {
            textView.background = dateItemBackgroundStart
        } else {
            textView.setBackgroundResource(R.drawable.com_jackiepenghe_rangedatepickerlibrary_default_date_item_background_start)
        }
    }

    private fun setEndSelectBackground(textView: TextView) {
        if (dateItemBackgroundEnd != null) {
            textView.background = dateItemBackgroundEnd
        } else {
            textView.setBackgroundResource(R.drawable.com_jackiepenghe_rangedatepickerlibrary_default_date_item_background_end)
        }
    }

    private fun setSelectBackground(textView: TextView, date: Date) {
        if (date.isSingleSelect(dataRecyclerViewAdapter)) {
            if (dateItemBackgroundSingleSelect != null) {
                textView.background = dateItemBackgroundSingleSelect
                return
            }
        }
        if (dateItemBackgroundSelect != null) {
            textView.background = dateItemBackgroundSelect
            return
        }
        textView.setBackgroundColor(
            ContextCompat.getColor(
                textView.context,
                R.color.com_jackiepenghe_rangedatepickerlibrary_default_date_item_background_select_color
            )
        )
    }

    private fun setEmptyBackground(textView: TextView) {
        if (dateItemBackgroundEmpty != null) {
            textView.background = dateItemBackgroundEmpty
        } else {
            textView.setBackgroundColor(
                ContextCompat.getColor(
                    textView.context,
                    R.color.com_jackiepenghe_rangedatepickerlibrary_default_date_item_background_empty_color
                )
            )
        }
    }

    private fun setDisableBackground(textView: TextView) {
        if (dateItemBackgroundEndDisable != null) {
            textView.background = dateItemBackgroundEndDisable
        } else {
            textView.setBackgroundColor(
                ContextCompat.getColor(
                    textView.context,
                    R.color.com_jackiepenghe_rangedatepickerlibrary_default_date_item_background_disable_color
                )
            )
        }
    }

    private fun setNormalBackground(textView: TextView) {
        if (dateItemBackgroundNormal != null) {
            textView.background = dateItemBackgroundNormal
        } else {
            textView.setBackgroundColor(
                ContextCompat.getColor(
                    textView.context,
                    R.color.com_jackiepenghe_rangedatepickerlibrary_default_date_item_background_normal_color
                )
            )
        }
    }
}
